
import router from './router'
import store from './store'

router.beforeEach(async(to, from, next) => {
  if (store.state.user.token) {
    if (to.path === '/login') {
      next()
    } else {
      if (!store.state.user.userInfo.userId) {
        await store.dispatch('user/getUserInfo')
        const routes = await store.dispatch('permission/filterRoutes', store.state.user.userInfo.roles.menus)
        // 结果刷新之后寻找路由快于合拼添加动态路由 进入404页面
        router.addRoutes([...routes, // 404 page must be placed at the end !!!
          { path: '*', redirect: '/404', hidden: true }])
        // 解决刷新后空白问题:如果没有找到路由页面就再次寻找
        next(to.path)
      } else { next() }
    }
  } else {
    const arr = ['/login', '/404']
    if (arr.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})
